#ifndef CONTROLLER_H
#define CONTROLLER_H

#include <QDomNode>
#include <QList>
#include <QString>
#include <QTime>
#include "action.h"
#include "board.h"
#include "sunlight.h"

#define PACKET_STARTEND         0x7E
#define PACKET_MIN_LEN          0x06
#define PACKET_CMD_BDINIT       0x00
#define PACKET_CMD_REMOTEINIT   0x01
#define PACKET_CMD_SET          0x02
#define PACKET_CMD_GET          0x03
#define PACKET_CMD_CURRENT      0x04
#define PACKET_CMD_NOTIFY       0x10
#define PACKET_CMD_NETSW        0x20
#define PACKET_CMD_NETSWUPDATE  0x21
#define PACKET_CMD_NACK         0xEE

#define TEMPERATURE_START       0x02
#define TEMPERATURE_CR          0x0D
#define TEMPERATURE_LF          0x0A

#include "netswitchboard.h"

struct PacketData {
    qint32      sendCount;
    QTime       sendTime;
    QByteArray  dataBuf;
    int         boardSync;
    int         timerAction;
};

class Controller
{
public:
    Controller();

    bool loadController(const QString fileName, const int cid, const bool isHeating);
    bool loadAction(const QString fileName);
    bool loadSunLight(const QString fileName);
    bool loadNetSwitch(const QString fileName);
    void parseNetSWBoard(QDomNode node, NetSwitchBoard& netswitchboard);
    void parseNetSwitch(QDomNode node, NetSwitchBoard& netswitchboard);
    void packetNetSWupdate(QList<PacketData>& packets, int swbid, int sweid, int status, int timerAction=0);
    void packetNetSWACK(QList<PacketData>& packets, int swbid, int sweid, int status, int timerAction=0);

    int boardType(int bid);
    void setRelayStatus(int bid, int rid, int status, QObject *timer=NULL, int timerDelay=-1);

    Relay *relay(int bid, int rid);
    Relay *timerRelay(int timerId, int *bid=NULL);

    int currentStatus(Relay *pRelay);

    QString packetTcpConnect() const;
    QString packetTcpUpdate(int bid, int rid) const;
    QString packetTcpReboot() const;

    void packetBoardInit(QList<PacketData>& packets);
    void packetBoardSync(QList<PacketData>& packets, int bid=-1);
    void packetRelaySet(QList<PacketData>& packets, int bid, int rid, int status, int timerAction=0);
    void packetRelayGet(QList<PacketData>& packets, int bid, int rid, int boardSync=0);
    void packetRelayCurrent(QList<PacketData>& packets, int bid, int rid);

    void temperatureSet(QList<PacketData>& packets, short set);
    void temperatureGet(QList<PacketData>& packets);

    void sendSms(int bid, int rid);
    void sendSms2(int bid, int rid, int status);

private:
    void clear();

    void parseBoard(QDomNode node, Board& board);
    void parseRelay(QDomNode node, Board& board);

public:
    int mId;
    bool mIsHeating;
    QString mName;
    QList<Board> mBoards;
    Action mAction;
    SunLight mSunLight;

    QString mSmsUrl;
    QString mSmsFrom;
    QString mSmsTos;

    QList<NetSwitchBoard> mNetSWBoards;
};

#endif // CONTROLLER_H
